
<template>
  <div>
    <div>
      <!-- 树形控件 -->
      <el-tree
        ref="tree"
        :data="treeData"
        :props="{ label: 'name' }"
        default-expand-all
        check-strictly
        show-checkbox
        node-key="id"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionListAPI } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleIdAPI, assignPermAPI } from '@/api/settings'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      treeData: []// 树形控件数据
    }
  },
  created() {
    // 调用获取权限数据列表的方法
    this.getPermissionList()

    // 调用获取当前角色权限的方法
    this.getRole()
  },
  methods: {
    // 声明获取权限数据列表
    async getPermissionList() {
      // 调接口
      const res = await getPermissionListAPI()

      // 转换数据,并赋值
      this.treeData = tranListToTreeData(res.data, '0')
    },

    // 声明获取当前角色权限
    async getRole() {
      // 调接口,拿数据
      const res = await getRoleIdAPI(this.roleId)

      // 传数据,数据回填,setCheckedKeys需要配合node-key,参数是个数组
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },

    // 确定按钮
    async setRolesBtn() {
      // 获取已选key
      const permIds = this.$refs.tree.getCheckedKeys()

      // 调接口传参
      const res = await assignPermAPI({ id: this.roleId, permIds })
      console.log(res)

      // 反馈用户
      this.$message.success(res.message)

      // 关闭弹窗
      this.$emit('close')
    },

    // 取消按钮
    cancelButton() {
      this.$emit('close')
    }

  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
